package com.booza.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.booza.constants.DatabaseConstants;
import com.booza.model.CreditCardDetails;

/**
 * A DAO implementation class for credit card details table.
 * 
 * @see CreditCardDetailsDAO
 */
@Transactional
public class CreditCardDetailsDAOImpl implements CreditCardDetailsDAO
{
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	@Override
	public CreditCardDetails findById(Integer id)
	{
		return (CreditCardDetails) sessionFactory.getCurrentSession().get(CreditCardDetails.class, id);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<CreditCardDetails> findCCForUser(int accountId, String cardType)
	{
		if (cardType == null || cardType.trim().equals("")) {
			return (List<CreditCardDetails>) sessionFactory
					.getCurrentSession()
					.createCriteria(CreditCardDetails.class)
					.add(Restrictions.eq("account." + DatabaseConstants.ACCOUNT_ID_COLUMN, accountId))
					.addOrder(Order.desc("expiryYear"))
					.addOrder(Order.desc("expiryMonth")).list();
		} 
		else {
			return (List<CreditCardDetails>) sessionFactory
					.getCurrentSession()
					.createCriteria(CreditCardDetails.class)
					.add(Restrictions.eq("cardType", cardType))
					.add(Restrictions.eq("account." + DatabaseConstants.ACCOUNT_ID_COLUMN, accountId))
					.addOrder(Order.desc("expiryYear"))
					.addOrder(Order.desc("expiryMonth")).list();
		}
	}

	@Override
	public void saveCreditCardDetails(CreditCardDetails cc)
	{
		sessionFactory.getCurrentSession().save(cc);
	}

	@Override
	public void deleteCreditCard(Integer cardId)
	{
		CreditCardDetails card = (CreditCardDetails) sessionFactory.getCurrentSession().load(CreditCardDetails.class,
				cardId);
		sessionFactory.getCurrentSession().delete(card);
	}

	@Override
	public CreditCardDetails findCCForUserWithCCNum(int accountId, String creditCardNumber, String cardType)
	{
		return (CreditCardDetails) sessionFactory.getCurrentSession().createCriteria(CreditCardDetails.class)
				.add(Restrictions.eq("cardNumber", creditCardNumber)).add(Restrictions.eq("cardType", cardType))
				.add(Restrictions.eq("account." + DatabaseConstants.ACCOUNT_ID_COLUMN, accountId)).uniqueResult();
	}
}
